package com.qianfeng.lingshijia;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

import java.util.Calendar;
import java.util.List;

import adapter.SecKillListAdapter;
import entity.SecKillEntity;
import utils.Constants;
import utils.DownloadUtils;

public class SecKillActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {

    private TextView  hoursTv, minutesTv, secondsTv;//时分秒显示的view
    private long time=System.currentTimeMillis();
    //导航条设置内容
    TextView nav_title;

    private long mHour =0;
    private long mMin = 0;
    private long mSecond =0;// 小时,分钟,秒
    private boolean isRun = true;

    PullToRefreshListView listView;
    String t = "0"; //秒杀链接 参数
    String url = null;

    List<SecKillEntity.DataEntity.ProductListEntity> data;
    SecKillListAdapter secKillListAdapter;

    RadioGroup radioGroup;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sec_kill);
        Intent intent = getIntent();
        if (intent != null)
        {
            url = intent.getStringExtra("url");
        }
        initView();
        startRun();
        loadData();
    }

    private void initView()
    {
        //列表
        listView = (PullToRefreshListView) findViewById(R.id.secKill_listView);
        secKillListAdapter = new SecKillListAdapter(getApplicationContext());
        listView.setAdapter(secKillListAdapter);
        //设置下拉刷新
        reflesh(listView);
        //listview添加脚部，也就是活动规则
        ImageView imageView = new ImageView(getApplicationContext());
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        AbsListView.LayoutParams params = new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT);
        imageView.setLayoutParams(params);
        imageView.setImageResource(R.drawable.activity_rule);
        //拿到PullToRefreshListView 里面的ListView 进行addView
        ListView mListView =  listView.getRefreshableView();
        mListView.addFooterView(imageView);

        //头部导航，设置内容以及倒计时
        nav_title = (TextView) findViewById(R.id.id_nav_title);
        nav_title.setText("限时限量  疯狂秒杀");

        hoursTv = (TextView) findViewById(R.id.hours_tv);
        minutesTv = (TextView) findViewById(R.id.minutes_tv);
        secondsTv = (TextView) findViewById(R.id.seconds_tv);

        //计时
        final Calendar mCalendar=Calendar.getInstance();
        mCalendar.setTimeInMillis(time);
        mHour = 20-mCalendar.get(Calendar.HOUR_OF_DAY);
        mMin = 60-mCalendar.get(Calendar.MINUTE);
        mSecond = 60- mCalendar.get(Calendar.SECOND);
        if(mHour>0 && mMin>0 && mSecond>0){
            // countDown.setVisibility(View.VISIBLE);
        }

        //RadioGroup切换时数据变更
        radioGroup = (RadioGroup) findViewById(R.id.rg_menu);
        radioGroup.setOnCheckedChangeListener(this);

        //默认中间按钮选中
      /*  RadioButton radioButton = (RadioButton) findViewById(R.id.rb_today);
        radioButton.setChecked(true);*/

    }

    private void loadData()
    {
        RequestParams params = new RequestParams();
        params.addBodyParameter("t", t);
        DownloadUtils.postJson(Constants.URL.SEC_KILL_URL, new RequestCallBack<String>()
        {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo)
            {
                if (responseInfo != null)
                {
                    String response = responseInfo.result;
                    Gson gson = new Gson();
                    SecKillEntity entity = gson.fromJson(response, SecKillEntity.class);
                    secKillListAdapter.setData(entity.getData().getProductList());
                    listView.onRefreshComplete();
                }

            }

            @Override
            public void onFailure(HttpException error, String msg)
            {
                error.printStackTrace();
                listView.onRefreshComplete();
            }
        }, params);
    }

    /**
     * 刷新设置
     * @param listview
     */
    private void reflesh(PullToRefreshListView listview)
    {
        listview.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        ILoadingLayout startLabels = listview.getLoadingLayoutProxy(true,false);
        startLabels.setPullLabel("下拉刷新...");// 刚下拉时，显示的提示
        startLabels.setRefreshingLabel("正在载入...");// 刷新时
        startLabels.setReleaseLabel("放开刷新...");// 下来达到一定距离时，显示的提示


        listview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                loadData();
            }
        });
    }


    /**
     * 定时器设置
     */
    private final Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg){
            if (msg.what==1) {
                computeTime();
                hoursTv.setText(mHour+"");
                if(mHour<10){
                    hoursTv.setText("0"+mHour);
                }
                minutesTv.setText(mMin+"");
                if(mMin<10){
                    minutesTv.setText("0"+mMin);
                }
                secondsTv.setText(mSecond+"");
                if(mSecond<10){
                    secondsTv.setText("0"+mSecond);
                }
                if (mHour==0&&mMin==0&&mSecond==0) {
                    //  countDown.setVisibility(View.GONE);
                }
            }
        }
    };
    private void startRun() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                while (isRun) {
                    try {
                        Thread.sleep(1000); // sleep 1000ms
                        Message message = Message.obtain();
                        message.what = 1;
                        handler.sendMessage(message);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    private void computeTime() {
        mSecond--;
        if (mSecond < 0) {
            mMin--;
            mSecond = 59;
            if (mMin < 0) {
                mMin = 59;
                mHour--;
                if (mHour < 0) {
                    // 倒计时结束
                    mHour = 23;
                    // countDown.setVisibility(View.GONE);

                }
            }
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId)
    {
        switch (checkedId)
        {
            case R.id.rb_yesterday:
                nav_title.setText("本场还有宝贝可以秒杀哦");
                t = "-1";
                if(mHour > 24){
                    mHour -= 24;
                }
                break;
            case R.id.rb_today:
                nav_title.setText("限时限量  疯狂秒杀");
                t = "0";
                if(mHour > 24){
                    mHour -= 24;
                }
                break;
            case R.id.rb_tomorrow:
                nav_title.setText("限时限量  疯狂秒杀");
                mHour += 24;
                t = "1";
                break;
        }
        loadData();
    }

    public void back(View view)
    {
        this.finish();
    }
}
